package com.example.intercept;

import com.example.annotation.Login;
import com.example.exception.MyException;
import com.example.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 拦截器
 * */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    //    每次请求前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        定义注解变量
        Login anno;
//        判断当前请求是否为接口方法
        if (handler instanceof HandlerMethod) {
//            获取方法上的login注解
            anno = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }
//        如果anno为null  代表没有获取到方法上的login注解  即方法没有被login修饰  就不需要登陆验证
        if (anno == null) {
            return true;
        }

//        获取token信息
        String token = request.getHeader("token");
        if (token != null && !"".equals(token)) {
            try {
                Claims claims = jwtUtil.getTokenBody(token);
                String account = claims.getSubject();
                request.setAttribute("account", account);
            } catch (Exception e) {
                throw new MyException("登录凭证过期,请重新登录");
            }
        } else {
            throw new MyException("未获取登陆凭证,请先登录 ");
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
